package com.youxin.logprocess.controller;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.youxin.busfoundation.config.MonitorBaseBean;
import com.youxin.busfoundation.config.MonitorWebConfig;
import com.youxin.busfoundation.net.WebDetectController;
import com.youxin.foundation.lang.BaseException;
import com.youxin.foundation.utils.thread.ScheduleThreadPool;
import com.youxin.logprocess.common.MonitorGlobalConfig;
/**
 * 监控Web
 * @author yingde.cao
 *
 */
public class MonitorWebController extends BaseMonitorController{
	private static Logger logger = Logger.getLogger(MonitorWebController.class);
	private MonitorWebConfig config;
	private static MonitorWebController controller = new MonitorWebController();

	public static void initConfig(MonitorWebConfig config) {
		controller.setConfig(config);
	}
	
	public MonitorWebConfig getConfig() {
		return config;
	}

	public void setConfig(MonitorWebConfig config) {
		this.config = config;
	}

	public static MonitorWebController instance(){
		return controller;
	}
	
	@Override
	public MonitorBaseBean getMonitorBean() {
		return config;
	}

	/**
	 * 执行方法
	 */
	public void execute() {
		if(config==null)
		{
			throw new BaseException("请配置mointor.mysql的config");
		}
		if (config.getMonitor() != MonitorGlobalConfig.MONITOR_ON) {
			return;
		}
		
		for(String hosts:config.getUrls())
		{
			ScheduleThreadPool.scheduleWithFixedDelay(new Runnable() {
				@Override
				public void run() {
					try {
						visitWeb(hosts);
					} catch (Exception e) {
						logger.error("连接"+hosts+"异常:",e);
						adds(hosts, e);
					}
				}
			}, config.getInterval(), 1000);
		}		
	}
	
	private void visitWeb(String hosts)
	{
		boolean isSuccess=false;
		String[] urls=hosts.split(",",0);
		for(String url:urls)
		{
			url=StringUtils.trimToEmpty(url);
			if(url.length()==0){
				continue;
			}
			isSuccess=false;
			try {
				isSuccess=WebDetectController.httpGetSuccess(url);
			} catch (Exception e) {
				logger.error("访问地址:"+url,e);
				add(url,e);
			}
			if(!isSuccess)
			{
				add(url, "访问失败:"+url);
			}
		}
	}
}
